<template>
  <!-- 增加加载状态和错误处理 -->
  <div v-if="loading" class="loading-container">
    <van-loading type="spinner" size="30px"/>
  </div>

  <div v-else-if="error" class="error-container">
    <van-empty description="获取用户信息失败"/>
  </div>

  <div v-else>
    <!-- 用户信息展示区域 -->
    <van-card
        style="margin: 20px 0 10px 0; padding: 0 5px;"
        :thumb="user.avatarUrl"
    >
      <template #title>
        <div class="user-title">{{ user.username }}</div>
      </template>
      <template #tags>
        <van-tag plain type="danger" v-for="tag in user.tags || []" :key="tag"
                 style="margin-right: 8px; margin-top: 8px">
          {{ tag }}
        </van-tag>
      </template>
    </van-card>

    <!-- 用户其他信息展示 -->
    <van-cell-group style="margin: 10px 0;">
      <van-cell title="账号" :value="user.userAccount || '未知'"/>
      <van-cell title="个人简介" :value="user.profile || '未知'"/>
      <van-cell title="星球编号" :value="user.planetCode || '未知'"/>
      <van-cell title="性别" :value="Number(user.gender) === 0 ? '男' : '女'"/>
    </van-cell-group>

    <!-- 操作按钮 -->
    <div class="button-container">
      <van-button v-if="followStatus === false" type="primary" size="large" @click="doFollowUser(user.id)">关注
      </van-button>
      <van-button v-if="followStatus === true" type="warning" size="large" @click="doCancelFollowUser(user.id)">
        取消关注
      </van-button>
      <van-button type="default" size="large">发送消息</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getUserById } from '../../api/User.ts';
import type { UserType } from "../../models/User";
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant';
import { deleteFollowUser, followUser, getFollowStatus } from "../../api/Follow.ts";

const route = useRoute();
const user = ref<UserType>({} as UserType);
const loading = ref(true);
const error = ref(false);

// 定义关注状态映射
const followStatusMap = ref<Record<number, boolean>>({});
const followStatus = ref<boolean>(false); // 当前用户的关注状态

onMounted(async () => {
  loading.value = true;
  error.value = false;

  const userIdStr = route.query.userId as string;
  if (!userIdStr || isNaN(Number(userIdStr))) {
    showFailToast('用户加载错误');
    error.value = true;
    loading.value = false;
    return;
  }

  const userId = Number(userIdStr);
  try {
    const result = await getUserById(userId);
    user.value = result.data;
    if (user.value.tags) {
      user.value.tags = JSON.parse(user.value.tags);
    }
  } catch (err) {
    console.error('获取用户信息失败', err);
    showFailToast('获取用户信息失败');
    error.value = true;
  } finally {
    loading.value = false;
  }
});

// 获取当前用户关注状态
const fetchFollowStatus = async () => {
  if (!user.value?.id) return;
  const res = await getFollowStatus(user.value.id);
  if (res.code === 0) {
    followStatus.value = res.data;
    followStatusMap.value[user.value.id] = res.data;
  } else {
    showFailToast('获取关注状态失败');
  }
};

// 关注用户
const doFollowUser = async (id: number) => {
  const result = await followUser(id);
  if (result.code === 0 && result.data) {
    showSuccessToast("关注成功");
    followStatusMap.value[id] = true;
    followStatus.value = true;
  } else {
    showFailToast("关注失败" + (result.description ? `：${result.description}` : ''));
  }
}

// 取关用户
const doCancelFollowUser = async (id: number) => {
  showConfirmDialog({
    title: '消息确认',
    message: '您确定要取消关注吗',
  }).then(async () => {
    const result = await deleteFollowUser(id);
    if (result.code === 0 && result.data) {
      showSuccessToast("取消关注成功");
      followStatusMap.value[id] = false;
      followStatus.value = false;
    } else {
      showFailToast("取消关注失败" + (result.description ? `：${result.description}` : ''));
    }
  }).catch(() => {
    // 取消操作
  });
}

// 监听用户ID变化，自动更新关注状态
watch(
    () => user.value.id,
    (newId) => {
      if (newId) {
        fetchFollowStatus();
      }
    },
    { immediate: true, deep: true }
);

</script>

<style scoped>
.loading-container, .error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.button-container {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  gap: 16px;
}

.user-title {
  margin: 6px 0;
  font-size: 20px;
  font-weight: bold;
}
</style>